package com.heiyanqiang.controller;

import com.heiyanqiang.domain.Role;
import com.heiyanqiang.domain.UserInfo;
import com.heiyanqiang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;




    //用户关联角色
    //addRoleToUser.do
    @RequestMapping("/addRoleToUser.do")
    public String addRoleToUser(@RequestParam(required = true,name = "userId")
                                        Integer userId,@RequestParam(required = true,name = "ids") Integer[] roleIds){
        userService.addRolesToUser(userId,roleIds);
        return "redirect:findAll.do";
    }


    //查询用户及用户可以添加的角色
    //user/findUserByIdAndAllRole.do
    @RequestMapping("/findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(@RequestParam(required = true,name = "id") Integer userId) throws Exception{

        ModelAndView mv = new ModelAndView();
        UserInfo userInfo =  userService.findById(userId) ;
        List<Role> otherRoles = userService.findOtherRoles(userId) ;
        mv.addObject("user",userInfo);
        mv.addObject("roleList",otherRoles);
        mv.setViewName("user-role-add");
        return mv;
    }

    //获取用户信息
    @RequestMapping("/findById.do")
    public ModelAndView finById(Integer id) throws Exception{

        ModelAndView mv = new ModelAndView();
        UserInfo userInfo =  userService.findById(id);
        mv.addObject("user",userInfo);
        mv.setViewName("user-show");
        return mv;
    }

    //添加用户
    @RequestMapping("/save.do")
    public String save(UserInfo userInfo) throws Exception{
        userService.save(userInfo);
        return "redirect:findAll.do";
    }

    //查询所有用户
    @RequestMapping("/findAll.do")
    public ModelAndView finaAll() throws Exception{
        ModelAndView mv = new ModelAndView();
        List<UserInfo> userList= userService.findAll();

        mv.addObject("userList",userList);
        mv.setViewName("user-list");
        return mv;
    }

}
